#!/bin/bash

# 自建服务器部署脚本
# 适用于 Ubuntu 20.04+ / CentOS 8+

echo "🚀 开始部署 Delivery Record Frontend..."

# 1. 系统更新
echo "📦 更新系统包..."
sudo apt update && sudo apt upgrade -y

# 2. 安装 Node.js 18+
echo "⚙️ 安装 Node.js..."
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt-get install -y nodejs

# 3. 安装 PM2 进程管理器
echo "🔧 安装 PM2..."
sudo npm install -g pm2

# 4. 安装 Nginx
echo "🌐 安装 Nginx..."
sudo apt install -y nginx

# 5. 克隆项目（需要先上传到Git仓库）
echo "📁 克隆项目..."
# git clone https://github.com/yourusername/delivery-record-fronted.git
# cd delivery-record-fronted

# 6. 安装依赖
echo "📦 安装项目依赖..."
npm install

# 7. 构建项目
echo "🏗️ 构建项目..."
npm run build

# 8. 创建生产环境配置
echo "⚙️ 创建环境配置..."
cat > .env.production << EOF
NODE_ENV=production
PORT=3001
DATABASE_PATH=/var/lib/delivery-record/delivery-management.db
BACKUP_PATH=/var/lib/delivery-record/backups
EOF

# 9. 创建数据目录
echo "📁 创建数据目录..."
sudo mkdir -p /var/lib/delivery-record/backups
sudo chown -R $USER:$USER /var/lib/delivery-record
cp data/delivery-management.db /var/lib/delivery-record/

# 10. 配置 PM2
echo "🔧 配置 PM2..."
cat > ecosystem.config.js << EOF
module.exports = {
  apps: [{
    name: 'delivery-record-frontend',
    script: 'node_modules/.bin/next',
    args: 'start',
    instances: 'max',
    exec_mode: 'cluster',
    env: {
      NODE_ENV: 'production',
      PORT: 3001
    },
    log_file: '/var/log/delivery-record/app.log',
    error_file: '/var/log/delivery-record/error.log',
    out_file: '/var/log/delivery-record/out.log',
    log_date_format: 'YYYY-MM-DD HH:mm:ss',
    max_memory_restart: '1G',
    watch: false,
    ignore_watch: ['node_modules', 'data', 'logs']
  }]
};
EOF

# 11. 创建日志目录
sudo mkdir -p /var/log/delivery-record
sudo chown -R $USER:$USER /var/log/delivery-record

# 12. 启动应用
echo "🚀 启动应用..."
pm2 start ecosystem.config.js
pm2 save
pm2 startup

# 13. 配置 Nginx 反向代理
echo "🌐 配置 Nginx..."
sudo tee /etc/nginx/sites-available/delivery-record << EOF
server {
    listen 80;
    server_name your-domain.com;  # 替换为您的域名
    
    location / {
        proxy_pass http://localhost:3001;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_cache_bypass \$http_upgrade;
    }
    
    # 静态文件缓存
    location /_next/static {
        proxy_pass http://localhost:3001;
        add_header Cache-Control "public, immutable, max-age=31536000";
    }
    
    # API 请求
    location /api {
        proxy_pass http://localhost:3001;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
    }
}
EOF

# 14. 启用站点
sudo ln -s /etc/nginx/sites-available/delivery-record /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx

# 15. 设置防火墙
echo "🔒 配置防火墙..."
sudo ufw allow 80
sudo ufw allow 443
sudo ufw allow 22
sudo ufw --force enable

# 16. 创建备份脚本
echo "💾 创建备份脚本..."
cat > backup.sh << 'EOF'
#!/bin/bash
DATE=$(date +"%Y%m%d_%H%M%S")
BACKUP_DIR="/var/lib/delivery-record/backups"
DB_PATH="/var/lib/delivery-record/delivery-management.db"

# 创建数据库备份
cp "$DB_PATH" "$BACKUP_DIR/delivery-management-backup-$DATE.db"

# 保留最近30天的备份
find "$BACKUP_DIR" -name "delivery-management-backup-*.db" -mtime +30 -delete

echo "Database backup completed: $BACKUP_DIR/delivery-management-backup-$DATE.db"
EOF

chmod +x backup.sh

# 17. 设置自动备份 (每天凌晨2点)
echo "⏰ 设置自动备份..."
(crontab -l 2>/dev/null; echo "0 2 * * * /home/$USER/delivery-record-fronted/backup.sh") | crontab -

# 18. 健康检查脚本
cat > healthcheck.sh << 'EOF'
#!/bin/bash
URL="http://localhost:3001"
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" "$URL")

if [ "$HTTP_CODE" -eq 200 ]; then
    echo "✅ Application is healthy"
    exit 0
else
    echo "❌ Application is unhealthy (HTTP $HTTP_CODE)"
    # 重启应用
    pm2 restart delivery-record-frontend
    exit 1
fi
EOF

chmod +x healthcheck.sh

# 19. 设置监控 (每5分钟检查一次)
(crontab -l 2>/dev/null; echo "*/5 * * * * /home/$USER/delivery-record-fronted/healthcheck.sh") | crontab -

echo "✅ 部署完成！"
echo "📝 部署信息："
echo "   - 应用端口: 3001"
echo "   - Nginx端口: 80"
echo "   - 数据库: /var/lib/delivery-record/delivery-management.db"
echo "   - 备份目录: /var/lib/delivery-record/backups"
echo "   - 日志目录: /var/log/delivery-record"
echo ""
echo "🔧 管理命令："
echo "   - 查看状态: pm2 status"
echo "   - 查看日志: pm2 logs"
echo "   - 重启应用: pm2 restart delivery-record-frontend"
echo "   - 手动备份: ./backup.sh"
echo "   - 健康检查: ./healthcheck.sh"